function setItem (name, item) {
  localStorage.setItem(name, JSON.stringify(item))
}

function getItem (name) {
  return JSON.parse(localStorage.getItem(name) || '[]')
}

export default {
  // { id: 商品id, count: 购买数量，selected: false  }
  state: {
    // [{id:13,count:2,selected:true},{},{}]
    car: getItem('car'),
    // 点击结算就购买的商品
    buy: getItem('buy')
  },
  mutations: {
    // 添加物品
    addShopcar (state, goodsinfo) {
      let flag = false
      state.car.some((item) => {
        if (item.id === goodsinfo.id) {
          item.count += parseInt(goodsinfo.count)
          flag = true
          return flag
        }
      })

      if (!flag === true) {
        state.car.push(goodsinfo)
      }
      setItem('car', state.car)
      // var flag = false
      // state.car.some(item => {
      //   if (item.id === goodsinfo.id) {
      //     item.count += parseInt(goodsinfo.count)
      //     flag = true
      //     return flag
      //   }
      // })
      // if (!flag === true) {
      //   state.car.push(goodsinfo)
      // }
      // setItem('car', state.car)
    },
    updatecountInfo (state, newval) {
      state.car.some((item) => {
        if (item.id === newval.goodid) {
          item.count = parseInt(newval.count)
          return true
        }
      })
      setItem('car', state.car)
    }
  },
  actions: {},
  getters: {
    // 获取所有商品的购买数量
    getGoodsCount (state) {
      var goods = {}
      state.car.forEach((item) => {
        goods[item.id] = item.count
      })
      return goods
    },
    // 判断选中
    getGoodsSelected (state) {
      const goods = {}
      state.car.forEach((item) => {
        goods[item.id] = item.selected
      })
      return goods
    },
    // 选中的数量和
    getSelectedCount (state) {
      var count = 0
      state.car.forEach((item) => {
        if (item.selected) {
          count += item.count
        }
      })
      return count
    },
    // 获取选中的商品
    getSelectedGood (state) {
      var good = {}
      state.car.forEach((item) => {
        if (item.selected) {
          good[item.id] = item
        }
      })
      return good
    },
    // 获取购买的商品
    getBuy (state) {
      var good = {}
      state.buy.forEach((item) => {
        good[item.id] = item
      })
      return good
    }
  },
  namespaced: true
}
